﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BlackBird.DataAccess
{
	public class AccountDataAccess
	{
		public static bool ValidateUser(string username, string password, out user user)
		{
			user = null;
			var allUsers = GlobalObjectBuffer.AllUsers;

			var users = from u in allUsers
						where u.Name == username
						select u;

			//no user found
			if (users.Count() == 0)
				return false;
			//error happened.
			if (users.Count() != 1)
				throw new InvalidOperationException("More than one user has the same user name found");

			var onlyUser = users.ToList()[0];
			//password error
			if (password != onlyUser.Password)
				return false;

			//good
			user = onlyUser;
			return true;
		}

		public static user GetUserInfoByUserID(string userID)
		{

			var user = GlobalObjectBuffer.allUsers.FirstOrDefault(v => v.idUser == userID);
			if (user == null)
				throw new NullReferenceException("Get expected user info failed");
			return user;
        }

        public static user GetUserInfoByUserName(string userName)
        {

            var user = GlobalObjectBuffer.allUsers.FirstOrDefault(v => v.Name == userName);
            if (user == null)
                throw new NullReferenceException("Get expected user info failed");
            return user;
        }

		public static void ChangeUserPassword(string userId, string newPassword)
		{
			using (var context = new blackbirdEntities())
			{
				var currentuser = context.user.FirstOrDefault(v => v.idUser == userId);
				currentuser.Password = newPassword;

				context.SaveChanges();
			}

			user us = GetUserInfoByUserID(userId);
				us.Password = newPassword;
		}
    }
}